const cubic = (value: number) => Math.pow(value, 3);

const easeInOutCubic = (value: number) =>
  value < 0.5 ? cubic(value * 2) / 2 : 1 - cubic((1 - value) * 2) / 2;

/**
 * 跳转位置函数
 * @param site 要去的位置
 * @param time 时间
 */
export const scrollTo = (site: number, time = 500, element?: any) => {
  element = element || document.documentElement;

  const rAF = window.requestAnimationFrame || (fun => setTimeout(fun, 16));
  // 记录开始时间
  const beginTime = Date.now();
  // 要去往的位置
  const toValue = site;
  // 滚动到顶部
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const frameFun = () => {
    // 进度，500ms 内将页面滚动到顶部
    const progress = (Date.now() - beginTime) / time;

    if (progress < 1) {
      // 根据进度修改 scrollTop 的值
      if (element.scrollTop < site) {
        element.scrollTop = toValue * easeInOutCubic(progress);
      } else {
        element.scrollTop =
          element.scrollTop -
          (element.scrollTop - site) * easeInOutCubic(progress);
      }
      rAF(frameFun);
    } else {
      element.scrollTop = site;
    }
  };
  rAF(frameFun);
};
